package com.bnz.controller;

import com.bnz.pojo.Classes;
import com.bnz.pojo.PageResult;
import com.bnz.pojo.Student;
import com.bnz.pojo.StudentVo;
import com.bnz.service.ClassesService;
import com.bnz.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private ClassesService classesService;

    @GetMapping("/list")
    public String findAll(Model model){
        List<Student> students=studentService.findAll();
        model.addAttribute("students",students);
        return "student/list";
    }

    @GetMapping("findByPage")
    public String findByPage(@RequestParam(defaultValue = "1",required = false) Integer page,
                             @RequestParam(defaultValue = "5",required = false) Integer pageSize,
                             Model model){

        PageResult<Student> pr=studentService.findByPage(page,pageSize);
        model.addAttribute("pr",pr);

        List<Classes> classes=classesService.findAll();
        model.addAttribute("classes",classes);

        return "student/list";
    }

    @RequestMapping("search")
    public String search(@RequestParam(defaultValue = "1",required = false) Integer page,
                         @RequestParam(defaultValue = "5",required = false) Integer pageSize,
                         StudentVo studentVo,
                         Model model){

        PageResult<String > pr=studentService.search(page,pageSize,studentVo);
        model.addAttribute("pr",pr);

        List<Classes> classes=classesService.findAll();
        model.addAttribute("classes",classes);

        System.out.println("stud = " + studentVo);
        if(studentVo == null){
            studentVo = new StudentVo();
        }

        model.addAttribute("stud",studentVo);

        return "student/list";
    }

    @RequestMapping("add")
    public String add(Student student){
        studentService.add(student);
        return "redirect:/student/search";
    }

    @RequestMapping("update")
    public String update(Student student){
        studentService.update(student);
        return "redirect:/student/search";
    }

    @RequestMapping("delete/{id}")
    public String delete(@PathVariable Integer id){
        studentService.delete(id);
        return "redirect:/student/search";
    }


}
